import './RiskRecharge.less'
import { App, Button, Form, Input, Radio, InputNumber, Table } from 'antd'
import { ProTable } from '@ant-design/pro-components'
import { useRef, useState } from 'react'
import { useModel } from '@umijs/max'
import QRCodeBox from '@/components/QRCodeBox/QRCodeBox'
import dayjs from 'dayjs'
import { useEffect } from 'react'

const RiskRecharge = () => {
  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [riskBalance, setRiskBalance] = useState(0)

  const [shopList, setShopList] = useState([]) // 店铺列表
  const [riskTypeMap, setRiskTypeMap] = useState([]) // 风控类型

  const [riskRechargeFormRef] = Form.useForm()

  const [amountTotal, setAmountTotal] = useState({}) // 金额统计

  const { message, modal } = App.useApp()
  const { GetRiskRechargePayQrcode, GetRiskBalance, ChartRiskListDetail, MerChart, GetRiskTypeMap } =
    useModel('RiskRecharge')
  const { platformType } = useModel('Global')
  const { GetShopSelections } = useModel('Goods')

  useEffect(() => {
    getShopList()
    getRiskTypeMap()
  }, [])

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()
    if (res) {
      setShopList(res.map(i => [i.id, i.shop_name]))
    }
  }

  // 查询风控余额
  const getRiskBalance = async () => {
    const res = await GetRiskBalance()
    if (res) {
      setRiskBalance(res.plat_left_chart || 0)
    }
  }

  // 获取风控类型
  const getRiskTypeMap = async () => {
    const res = await GetRiskTypeMap()
    if (res) {
      setRiskTypeMap(res.map(i => [i.deduction, i.deduction_name]))
    }
  }

  // 充值按钮
  const handleRecharge = () => {
    modal.confirm({
      width: 600,
      title: '风控充值',
      icon: null,
      content: (
        <div className='order_content'>
          <Form
            labelCol={{ span: 6 }}
            preserve={false}
            form={riskRechargeFormRef}
            name='risk_info'
            initialValues={{ pay_type: '1' }}
          >
            {platformType === 0 && (
              <Form.Item name='pay_type' label='支付类型 : ' rules={[{ required: true, message: '请选择支付类型' }]}>
                <Radio.Group>
                  <Radio value='1'>支付宝支付</Radio>
                  {/* <Radio value='2'>微信支付</Radio> */}
                </Radio.Group>
              </Form.Item>
            )}

            <Form.Item name='amount' label='充值金额 : ' rules={[{ required: true, message: '请输入充值金额' }]}>
              <InputNumber placeholder='请输入充值金额' style={{ width: '400px' }} />
            </Form.Item>

            <Form.Item name='note' label='备注 : ' rules={[{ required: false, message: '请输入备注' }]}>
              <Input.TextArea placeholder='请输入备注' style={{ width: '400px' }} />
            </Form.Item>
          </Form>
        </div>
      ),
      onOk: async () => {
        await riskRechargeFormRef.validateFields()
        const values = riskRechargeFormRef.getFieldsValue()

        // 平台端充值
        if (platformType === 0) {
          const res = await GetRiskRechargePayQrcode(values)
          if (res) {
            const qrData = {
              ...res,
              ...values
            }

            modal.info({
              width: 600,
              title: '',
              icon: null,
              content: <QRCodeBox qrData={qrData} />,
              okText: '关闭',
              onOk: () => {
                tableRef.current.reload()
              }
            })
          }
        }

        // 商家端充值
        if (platformType === 1) {
          let params = {
            amount: values.amount,
            subject: values.note,
            type: 4,
            chart_pass_way: 1
          }
          const res = await MerChart(params)
          if (res) {
            message.success('申请充值成功,请等待平台审核！')
          }
        }
      }
    })
  }

  const columns = [
    {
      title: '归属订单',
      dataIndex: 'order_sn'
    },
    {
      title: '客户姓名',
      dataIndex: 'cert_name'
    },
    {
      title: '查询店铺',
      dataIndex: 'merchant_name',
      hideInSearch: platformType === 1,
      hideInTable: platformType === 1,
      valueType: 'select',
      valueEnum: new Map(shopList)
    },
    {
      title: '查询项目',
      dataIndex: 'deduction_name',
      valueType: 'select',
      valueEnum: new Map(riskTypeMap)
    },
    {
      title: '消耗金额',
      dataIndex: 'amount',
      hideInSearch: true
    },
    {
      title: '查询时间',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      render: (text, record) => <div>{record.created_at}</div>,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    }
  ]

  return (
    <div className='risk_recharge'>
      <div className='risk_header'>
        <div className='risk_card'>
          <div className='risk_card_panel'>
            <div
              className='risk_card_panel_amount'
              style={{
                color: platformType === 0 ? '#313131' : '#ffffff'
              }}
            >
              {riskBalance}
            </div>
            {platformType === 0 && <img src='https://qny.weizulin.cn/images/202403281448635.png' />}
            {platformType === 1 && <img src='https://qny.weizulin.cn/images/202403281448636.png' />}
            <Button className='risk_card_panel_btn' onClick={handleRecharge}></Button>
          </div>
          <div className='risk_card_info'>
            <p className='risk_card_info_title'>充值须知：</p>
            {platformType === 0 && (
              <>
                <p>1.风控充值不需任何额外技术费用，一般充值为及时到账（特殊情况除外，请联系平台相关人员）。</p>
                <p>2.可以使用支付宝支付或者微信支付来进行充值风控费用。</p>
              </>
            )}

            {platformType === 1 && (
              <>
                <p>1.风控充值不需任何额外技术费用，充值为申请充值，输入充值金额后提交平台审核。</p>
                <p>2.充值后需要平台端审核，平台审核通过后风控充值即刻生效。</p>
              </>
            )}
          </div>
        </div>
      </div>
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const param = {
            page: params.current,
            page_size: params.pageSize,
            created_at_start: params.start,
            created_at_end: params.end,

            order_sn: params.order_sn,
            user_name: params.cert_name,
            deduction: params.deduction_name,
            merchant_id: params.merchant_name
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          await getRiskBalance()
          const res = await ChartRiskListDetail(param)

          setAmountTotal(res.other)

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey={() => Math.random()}
        scroll={{ x: 'max-content' }}
        columns={columns}
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 8
        }}
        summary={pageData => {
          return (
            <Table.Summary.Row>
              {columns.map((item, index) => {
                return (
                  <Table.Summary.Cell index={index} key={index}>
                    <div className='summary_cell'>
                      {index === 0 && <div className='summary_cell_item'>条件统计</div>}
                      {index === 4 && <div className='summary_cell_item'>{amountTotal.total_amount}</div>}
                    </div>
                  </Table.Summary.Cell>
                )
              })}
            </Table.Summary.Row>
          )
        }}
      />
    </div>
  )
}

export default RiskRecharge
